package com.rtype.GPSilencer;

import com.rtype.GPSilencer.helpers.ProfileDbAdapter;

import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.view.View;

public class ProfileDetails extends PreferenceActivity implements OnPreferenceChangeListener {
	
	public static final String KEY_PROFILENAME = "ProfileName";
	
	private EditTextPreference mProfileName;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.profile);
        mProfileName = (EditTextPreference)findPreference(KEY_PROFILENAME);
        mProfileName.setOnPreferenceChangeListener(this);
	}
	
	public void save(View v) {
		final EditTextPreference profileNameView = (EditTextPreference)findPreference(KEY_PROFILENAME);
		String profileName = profileNameView.getEditText().getText().toString();
		try {
			validate(profileName);
			ProfileDbAdapter mAdapter = new ProfileDbAdapter(this);
			mAdapter.open();
			mAdapter.create("location", 1, profileName, 5, 1);
			mAdapter.close();
			finish();
		} 
		catch(Exception e) {
			e.getMessage();
		}
	}
	
	public void cancel(View v) {
		finish();
	}
	
	private void validate(String profileName) throws Exception {
		if(profileName == null || "".equals(profileName)) {
			throw new Exception("Empty name!");
		}
	}

	@Override
	public boolean onPreferenceChange(Preference preference, Object newValue) {
		if(preference.getKey().equals(KEY_PROFILENAME)) {
			preference.setSummary((String)newValue);
			return true;
		}
		return false;
	}

}
